<template>
  <div>
    <el-dialog
      @open="open"
      :title="pageTitle"
      @close="cancel"
      :visible="showDialog"
    >
      <el-form ref="myform" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" placeholder="请选择">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="form.introduce" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addDepts">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartmentsApi,
  addDeptsApi,
  getDeptsByIdApi,
  editDeptsApi
} from '@/api/departments.js'
import { getUserSimpleApi } from '@/api/employees.js'
export default {
  props: ['showDialog', 'currentItem'],
  data () {
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称长度在1~50个字符',
            trigger: 'blur'
          },
          {
            validator: async (rule, value, callback) => {
              // 当前操作的item，currentItem
              // 所有的部门 接口
              const res = await getDepartmentsApi()
              if (!this.form.id) {
                res.data.depts.some(
                  item =>
                    item.name === value && item.pid === this.currentItem.id
                )
                  ? callback(new Error('部门名称不能重复'))
                  : callback()
              } else {
                res.data.depts.some(
                  item =>
                    // 找到和当前点击的同级部门
                    item.pid === this.currentItem.pid &&
                    item.name === value &&
                    // 当前点击的id不等于同级部门的id
                    item.id !== this.form.id
                )
                  ? callback(new Error('部门名称不能重复'))
                  : callback()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码长度在1~50个字符',
            trigger: 'blur'
          },
          {
            validator: async (rule, value, callback) => {
              const res = await getDepartmentsApi()
              if (!this.form.id) {
                res.data.depts.some(item => item.code === value)
                  ? callback(new Error('部门编码不能重复'))
                  : callback()
              } else {
                res.data.depts.some(
                  item => item.code === value && item.id !== this.form.id
                )
                  ? callback(new Error('部门编码不能重复'))
                  : callback()
              }
            },
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门介绍长度在1~300个字符',
            trigger: 'blur'
          }
        ]
      },
      userList: []
    }
  },
  methods: {
    async getUser () {
      const res = await getUserSimpleApi()
      this.userList = res.data
    },
    addDepts () {
      this.$refs.myform.validate(async valid => {
        if (valid) {
          try {
            if (!this.form.id) {
              // 新增
              await addDeptsApi({
                ...this.form,
                pid: this.currentItem.pid === '-1' ? '' : this.currentItem.id
              })
            } else {
              // 编辑
              await editDeptsApi(this.form)
            }

            this.$emit('updatedata')
            this.$message.success(this.form.id ? '编辑成功' : '新增成功')
            this.$emit('update:showDialog')
            this.form = {
              name: '',
              code: '',
              manager: '',
              introduce: ''
            }
          } catch (error) {
            console.log('失败')
          }
        }
      })
    },
    cancel () {
      this.$emit('update:showDialog')
      this.$refs.myform.resetFields()
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    open () {
      this.getUser()
    },
    async getDeptsById (id) {
      const res = await getDeptsByIdApi(id)
      this.form = res.data
    }
  },
  computed: {
    pageTitle () {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  }
}
</script>

<style></style>
